<?php

namespace App\Http\Controllers\Backend;

use App\Models\Permission;
use App\Models\PermissionGroup;
use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\PermissionRequest;

class PermissionController extends BaseController {

    public function index()
    {
        $permissions = Permission::paginate($this->pagesize);

        return view('backend.permission.index')->withPermissions($permissions);
    }


    public function create()
    {
        $permissionGroups = PermissionGroup::all();

        return view('backend.permission.create')->with('permissionGroups', $permissionGroups);
    }

    public function store(PermissionRequest $request)
    {
        $redirect = $request->get('redirect');

        $permission = new Permission();
        $permission->name         = $request->get('name');
        $permission->display_name = $request->get('display_name');
        $permission->group_id     = $request->get('group_id');
        $permission->description  = $request->get('description');
        $success = $permission->save();

        if($success) {
            return $this->responseCreatedSuccess('权限添加成功', ['redirect' => $redirect]);
        } else {
            return $this->responseCreatedFail('权限添加失败');
        }
    }

    public function show($id)
    {
        $permission = Permission::findOrFail($id);
        $permissionGroups = PermissionGroup::all();

        return view('backend.permission.show')->withPermission($permission)
                                              ->with('permissionGroups', $permissionGroups);;
    }

    public function update($id, PermissionRequest $request)
    {
        $redirect = $request->get('redirect');

        $permission = Permission::findOrFail($id);
        $permission->name         = $request->get('name');;
        $permission->display_name = $request->get('display_name');
        $permission->group_id     = $request->get('group_id');
        $permission->description  = $request->get('description');
        $success = $permission->save();

        if($success) {
            return $this->responseUpdatedSuccess('权限修改成功', ['redirect' => $redirect]);
        }else {
            return $this->responseUpdatedFail('权限修改失败');
        }
    }

    public function destroy($id, PermissionRequest $request)
    {
        $redirect = $request->get('redirect');

        $permission = Permission::findOrFail($id);
        $success = $permission->delete();

        if($success) {
            return $this->responseDeletedSuccess('权限删除成功', ['redirect' => $redirect]);
        }else {
            return $this->responseDeletedFail('权限删除失败');
        }
    }

}